package com.nbcio.pm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nbcio.common.mybatis.core.page.PageQuery;
import com.nbcio.common.mybatis.core.page.TableDataInfo;
import com.nbcio.common.core.utils.MapstructUtils;
import com.nbcio.common.core.utils.StringUtils;
import com.nbcio.pm.domain.PmProjectMember;
import com.nbcio.pm.domain.bo.PmProjectMemberBo;
import com.nbcio.pm.domain.vo.PmProjectMemberVo;
import com.nbcio.pm.mapper.PmProjectMemberMapper;
import com.nbcio.pm.service.IPmProjectMemberService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 项目成员Service业务层处理
 *
 * @author nbacheng
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class PmProjectMemberServiceImpl implements IPmProjectMemberService {

    private final PmProjectMemberMapper baseMapper;

    /**
     * 查询项目成员
     */
    @Override
    public PmProjectMemberVo queryById(Long memberId) {
        return baseMapper.selectVoById(memberId);
    }

    /**
     * 查询项目成员列表
     */
    @Override
    public TableDataInfo<PmProjectMemberVo> queryPageList(PmProjectMemberBo bo, PageQuery pageQuery) {
        Map<String, Object> params = bo.getParams();
        // 使用带关联查询的方法
        List<PmProjectMemberVo> list = baseMapper.selectVoListWithJoin(
            bo.getProjectId(),
            bo.getUserId(),
            bo.getRole(),
            bo.getIsActive(),
            bo.getRemark(),
            (String) params.get("beginJoinDate"),
            (String) params.get("endJoinDate")
        );
        
        // 手动分页
        int total = list.size();
        int start = (int) ((pageQuery.getPageNum() - 1) * pageQuery.getPageSize());
        int end = Math.min(start + (int) pageQuery.getPageSize(), total);
        
        List<PmProjectMemberVo> pageList = list.subList(start, end);
        
        TableDataInfo<PmProjectMemberVo> rspData = new TableDataInfo<>();
        rspData.setCode(200);
        rspData.setMsg("查询成功");
        rspData.setRows(pageList);
        rspData.setTotal(total);
        return rspData;
    }

    /**
     * 查询项目成员列表
     */
    @Override
    public List<PmProjectMemberVo> queryList(PmProjectMemberBo bo) {
        LambdaQueryWrapper<PmProjectMember> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<PmProjectMember> buildQueryWrapper(PmProjectMemberBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<PmProjectMember> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getProjectId() != null, PmProjectMember::getProjectId, bo.getProjectId());
        // 支持按用户ID查询（可能是逗号分隔的多个ID）
        if (StringUtils.isNotBlank(bo.getUserId())) {
            if (bo.getUserId().contains(",")) {
                // 多个用户ID，使用IN查询
                String[] userIds = bo.getUserId().split(",");
                lqw.in(PmProjectMember::getUserId, (Object[]) userIds);
            } else {
                // 单个用户ID，使用精确匹配或包含匹配
                lqw.and(wrapper -> wrapper
                    .eq(PmProjectMember::getUserId, bo.getUserId())
                    .or()
                    .like(PmProjectMember::getUserId, bo.getUserId() + ",")
                    .or()
                    .like(PmProjectMember::getUserId, "," + bo.getUserId() + ",")
                    .or()
                    .like(PmProjectMember::getUserId, "," + bo.getUserId())
                );
            }
        }
        lqw.eq(StringUtils.isNotBlank(bo.getRole()), PmProjectMember::getRole, bo.getRole());
        lqw.eq(bo.getIsActive() != null, PmProjectMember::getIsActive, bo.getIsActive());
        lqw.eq(StringUtils.isNotBlank(bo.getRemark()), PmProjectMember::getRemark, bo.getRemark());
        lqw.between(params.get("beginJoinDate") != null && params.get("endJoinDate") != null,
            PmProjectMember::getJoinDate, params.get("beginJoinDate"), params.get("endJoinDate"));
        return lqw;
    }

    /**
     * 新增项目成员
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByBo(PmProjectMemberBo bo) {
        PmProjectMember add = MapstructUtils.convert(bo, PmProjectMember.class);
        
        // 处理多用户ID：优先使用userIds，如果为空则使用userId
        if (bo.getUserIds() != null && !bo.getUserIds().isEmpty()) {
            // 使用userIds列表
            String userIdsStr = bo.getUserIds().stream()
                .map(String::valueOf)
                .collect(Collectors.joining(","));
            add.setUserId(userIdsStr);
        } else if (bo.getUserId() != null && !bo.getUserId().isEmpty()) {
            // 使用单个userId
            add.setUserId(bo.getUserId());
        }
        
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setMemberId(add.getMemberId());
        }
        return flag;
    }

    /**
     * 修改项目成员
     */
    @Override
    public Boolean updateByBo(PmProjectMemberBo bo) {
        PmProjectMember update = MapstructUtils.convert(bo, PmProjectMember.class);
        
        // 处理多用户ID：优先使用userIds，如果为空则使用userId
        if (bo.getUserIds() != null && !bo.getUserIds().isEmpty()) {
            // 使用userIds列表
            String userIdsStr = bo.getUserIds().stream()
                .map(String::valueOf)
                .collect(Collectors.joining(","));
            update.setUserId(userIdsStr);
        } else if (bo.getUserId() != null && !bo.getUserId().isEmpty()) {
            // 使用单个userId
            update.setUserId(bo.getUserId());
        }
        
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(PmProjectMember entity) {
        // TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除项目成员
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            // TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * 查询项目成员列表
     */
    @Override
    public List<PmProjectMemberVo> queryByProjectId(Long projectId) {
        return baseMapper.selectVoListWithJoin(projectId, null, null, true, null, null, null);
    }

    /**
     * 查询用户参与的项目列表
     */
    @Override
    public List<PmProjectMemberVo> queryByUserId(Long userId) {
        LambdaQueryWrapper<PmProjectMember> lqw = Wrappers.lambdaQuery();
        lqw.eq(PmProjectMember::getUserId, userId);
        lqw.eq(PmProjectMember::getIsActive, 1);
        return baseMapper.selectVoList(lqw);
    }

    /**
     * 检查用户项目权限
     */
    @Override
    public Boolean checkProjectPermission(Long userId, Long projectId, String permission) {
        LambdaQueryWrapper<PmProjectMember> lqw = Wrappers.lambdaQuery();
        lqw.eq(PmProjectMember::getUserId, userId);
        lqw.eq(PmProjectMember::getProjectId, projectId);
        lqw.eq(PmProjectMember::getIsActive, 1);
        PmProjectMember member = baseMapper.selectOne(lqw);
        if (member == null) {
            return false;
        }
        // TODO 根据角色和权限进行权限检查
        return true;
    }
}
